package com.gsdse.controller;

import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.gsdse.pojo.ApplyTime;
import com.gsdse.pojo.ReturnData;
import com.gsdse.pojo.apply;
import com.gsdse.service.ApplyService;
import com.gsdse.service.UserService;
import com.gsdse.utils.AliOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Slf4j
@RestController
public class ApplyController {

    @Autowired
    private ApplyService applyService;

    @Autowired
    private UserService userService;

    //文件上传
    @PostMapping("/uploadpdf")
    public ReturnData uploadpdf(MultipartFile pdf, String userId, String firstWilling, String secondWilling) throws IOException, ClientException {
        ReturnData returnData = new ReturnData();

        if ((StringUtils.isNotEmpty(userId)) && (StringUtils.isNotEmpty(firstWilling)) && (StringUtils.isNotEmpty(secondWilling)) && (pdf != null)) {
//            String realPath = servletContext.getRealPath("")+File.separator+"Uploadpdf"+File.separator;
//            String realPath = "/www/wwwroot/kj_recruit/file";
            String realPath = "/usr/local/src";
            //String realPath = "D:\\kjPdf";

            String originalFilename = pdf.getOriginalFilename();
            long timestamp = System.currentTimeMillis();
            //suffixName表示后缀名
            String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
            log.info(suffixName);
            String substring = originalFilename.substring(0, originalFilename.lastIndexOf("."));
            log.info(substring);

            //文件访问路径
            //String OnlinePath = "https://studynest.top/file/" + substring + timestamp + suffixName;
            //更换成OSS
            //String OnlinePath = "https://gsdse.cn/file/" + substring + timestamp + suffixName;
            String OnlinePath = AliOSSUtils.uploadFile(pdf,substring + timestamp + suffixName,"file");
            System.out.println(realPath);

//            String finalpath = "\\www\\server\\tomcat\\webapps\\gsdkj_recruit\\file\\" + substring + timestamp+ suffixName;
            //文件上传到服务器的路径
            String finalPath = realPath + File.separator + substring + timestamp + suffixName;
            System.out.println(finalPath);

            File file = new File(realPath);
            if (!file.exists()) {
                file.mkdir();
            }
//            String finalpath=realPath + File.separator + timestamp+suffixName;

            File fff = new File(finalPath);
            //上传文件
            pdf.transferTo(fff);
            //保存pdf地址到数据库
            //先查看之前有没有提交过
            apply apply = applyService.selectApplybyUserid(Integer.parseInt(userId));
            if (apply != null) {
                //提交过了，
                Integer applyId = apply.getApplyId();
                apply newApply = new apply();
                newApply.setApplyId(applyId);
                newApply.setUserId(Integer.parseInt(userId));
                newApply.setPdfUrl(OnlinePath);
                newApply.setTime(String.valueOf(timestamp));
                newApply.setFirstWilling(firstWilling);
                newApply.setSecondWilling(secondWilling);
                if(firstWilling.equals("0"))
                {
                    newApply.setFirstStatus("0");
                }
                else {
                    newApply.setFirstWilling(firstWilling);
                }
                if(secondWilling.equals("0")){
                    newApply.setSecondStatus("0");
                }
                else {
                    newApply.setSecondWilling(secondWilling);
                }
                boolean b = applyService.updateApply(newApply);
                if (b) {
                    returnData.setCode(0);
                    returnData.setMsg("重新提交成功");
                    returnData.setData(newApply);
                } else {
                    returnData.setCode(1);
                    returnData.setMsg("重新提交失败");
                }
            } else {
                //第一次提交
                apply a = new apply();
                a.setTime(String.valueOf(timestamp));
                a.setPdfUrl(finalPath);
                a.setFirstWilling(firstWilling);
                a.setSecondWilling(secondWilling);
                a.setUserId(Integer.parseInt(userId));
                log.info(a.toString());
                if(firstWilling.equals("0"))
                {
                    a.setFirstStatus("0");
                }
                else {
                    a.setFirstWilling(firstWilling);
                }
                if(secondWilling.equals("0")){
                    a.setSecondStatus("0");
                }
                else {
                    a.setSecondWilling(secondWilling);
                }
                boolean b = applyService.insertApply(a);
                if (b) {
                    returnData.setCode(0);
                    returnData.setMsg("提交成功");
                    returnData.setData(a);
                } else {
                    returnData.setCode(2);
                    returnData.setMsg("提交失败");
                }

            }
            //放入阻塞队列
            try {
                applyService.addApply2QueueAndPic(userId);
            } catch (InterruptedException e) {
                log.error("预发送面试二维码错误！",e);
                throw new RuntimeException(e);
            }
        } else {
            returnData.setCode(3);
            returnData.setMsg("参数缺省");
        }
        return returnData;
    }



    //根据用户Id查询用户志愿表
    @RequestMapping("/SelectUserWilling")
    public ReturnData SelectUserWilling(String userId) {
        ReturnData returnData = new ReturnData();
        if (userId == null) {
            returnData.setCode(1);
            returnData.setMsg("所传参数为空");
            return returnData;
        } else {
            apply apply = applyService.selectApplybyUserid(Integer.parseInt(userId));
            if (apply == null) {
                returnData.setCode(1);
                returnData.setMsg("用户志愿表不存在");
                return returnData;
            } else {
                returnData.setData(apply);
                returnData.setCode(0);
                returnData.setMsg("查询成功");
                return returnData;
            }
        }

    }


    //根据表Id查询用户志愿表
    @RequestMapping(value = "/SelectUserWillingByApplyId")
    public ReturnData SelectUserWillingByApplyId(@RequestParam(value = "applyId") Integer applyId) {
        ReturnData returnData = new ReturnData();
        if (applyId == null) {
            returnData.setCode(1);
            returnData.setMsg("用户ID为空");
            return returnData;
        } else {
            apply apply = applyService.selectApplyByApplyId(applyId);
            if (apply == null) {
                returnData.setCode(1);
                returnData.setMsg("用户志愿表不存在");
                return returnData;
            } else {

                returnData.setData(apply);
                returnData.setCode(0);
                returnData.setMsg("查询成功");
                return returnData;
            }
        }

    }

    //根据志愿查询用户志愿表
    //用department查applyId
    //即willing有哪个部门就推给哪个部门
    @RequestMapping("/selectApplyByWilling")
    public ReturnData selectApplyByWilling(String departmentId,String startTime,String endTime) {
        ReturnData returnData = new ReturnData();
//      List<apply> applies = applyService.selectApplyByWilling(department);
        List<apply> applyId = applyService.selectApplyByWillingAndTime(departmentId,startTime,endTime);
        if (applyId.isEmpty()) {
            returnData.setCode(1);
            returnData.setMsg("没有人报这个部门");
        } else {
            returnData.setData(applyId);
            returnData.setCode(0);
            returnData.setMsg("查询成功");
        }
        return returnData;
    }

    //志愿是否通过
    @RequestMapping("/willingPass")
    public ReturnData willingPass(String applyId, String firstStatus, String secondStatus) {
        ReturnData returnData = new ReturnData();
        if (StringUtils.isNotEmpty(applyId) && (StringUtils.isNotEmpty(firstStatus) || StringUtils.isNotEmpty(secondStatus))) {
            //查询出这条投递
            apply apply = applyService.selectApplyByApplyId(Integer.parseInt(applyId));
            boolean b = false;
            //设置志愿通过情况。1代表通过。
            if (secondStatus != null) {
                //如果没有第二志愿  secondStatus--->可能为0 or 1
                apply.setSecondStatus(secondStatus);
                b = applyService.updateApply(apply);
                //扔进阻塞队列 key:applyId value: 2(第二志愿)
                //applyService.addStatus2QueueToSend(applyId,2);

            }else if(firstStatus != null){
                apply.setFirstStatus(firstStatus);
                b = applyService.updateApply(apply);
                //扔进阻塞队列 key:applyId value: 1(第一志愿)
                //applyService.addStatus2QueueToSend(applyId,2);
            }
            if (b) {
                returnData.setData(apply);
                //放入阻塞队列
                try {
                    applyService.addApply2QueueAndText(apply.getApplyId());
                }
                catch (InterruptedException e)
                {
                    returnData.setCode(3);
                    returnData.setMsg("操作成功，但发送邮箱失败！");
                    log.error("apply放入队列异常！");
                    throw new RuntimeException(e);
                }

                returnData.setCode(0);
                returnData.setMsg("操作成功");
            } else {
                returnData.setCode(1);
                returnData.setMsg("操作失败");
            }
        } else {
            returnData.setCode(2);
            returnData.setMsg("参数错误");
        }
        return returnData;
    }


    //反选
    //想法是 两个按钮 反选哪个部门 哪个部门的status由前端先变为2，我们来接收
    //接收到哪个为2，我们把另外一个变为0。
    @RequestMapping("/reverseWilling")
    public ReturnData reverseWilling(String applyId, String firstStatus, String secondStatus) {
        ReturnData returnData = new ReturnData();
        if (StringUtils.isNotEmpty(applyId) && StringUtils.isNotEmpty(firstStatus) && StringUtils.isNotEmpty(secondStatus))
        {
            Boolean isOk = applyService.reverseWilling(Integer.parseInt(applyId), firstStatus, secondStatus);
            if(Boolean.FALSE.equals(isOk)){
                returnData.setCode(1);
                returnData.setMsg("更新失败");
            }
            returnData.setCode(0);
            returnData.setMsg("操作成功");
        } else {
            returnData.setCode(1);
            returnData.setMsg("参数错误");
        }
        return returnData;
    }


    //查询该志愿出现次数
    @RequestMapping("/countWilling")
    public ReturnData getCountByFirstWilling(String department,String startTime,String endTime)
    {
        ReturnData returnData = new ReturnData();
        Integer count = applyService.selectCountByFirstWilling(department,startTime,endTime);
        System.out.println(count);
        returnData.setData(count);
        returnData.setCode(0);
        returnData.setMsg("查询成功");
        return returnData;
    }

    //用户登录成功即生成apply设置userid
    @RequestMapping("/SetUserId")
    public ReturnData SetUserId(String userId,String applyId) {
        ReturnData returnData = new ReturnData();
        apply apply = applyService.selectApplybyUserid(Integer.parseInt(userId));
        if (apply == null) { //没有apply了，是新用户
            apply apply1= new apply();
            apply1.setUserId(Integer.parseInt(userId));
            apply1.setApplyId(Integer.parseInt(applyId));
            boolean b = applyService.insertApply(apply1);
            if (b) {
                returnData.setCode(0);
                returnData.setMsg("设置成功");
                returnData.setData(apply);
            }
        }
        else
        {
            returnData.setCode(1);
            returnData.setMsg("自动apply已存在");
        }
        return returnData;
    }

    @RequestMapping("/returnFalse")
    public boolean returnTure(){
        //审核就返回false，正式使用返回true（这样返回没错的！！）
        return true;
    }

    @GetMapping("/getApplyTime")
    public ReturnData getApplyTime() {
        return applyService.getApplyTime();
    }

    @PostMapping("/setApplyTime")
    public ReturnData setApplyTime(@RequestBody ApplyTime applyTime)
    {
        return applyService.setApplyTime(applyTime.getStartTime(),applyTime.getEndTime());
    }
}



